<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\Freelancer;

class FreelancerAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // 检查是否已认证
        if (!$request->user()) {
            return response()->json([
                'success' => false,
                'message' => '未认证，请先登录'
            ], 401);
        }

        // 检查用户是否为自由职业者
        if (!($request->user() instanceof Freelancer)) {
            return response()->json([
                'success' => false,
                'message' => '权限不足'
            ], 403);
        }

        $freelancer = $request->user();

        // 检查自由职业者状态
        if ($freelancer->status === 'suspended') {
            return response()->json([
                'success' => false,
                'message' => '账号已被暂停，请联系管理员'
            ], 403);
        }

        if ($freelancer->status === 'rejected') {
            return response()->json([
                'success' => false,
                'message' => '账号审核未通过，请重新提交资料'
            ], 403);
        }

        return $next($request);
    }
}
